package com.wondream.myframework.heima_concurrent;

import java.util.ArrayList;
import java.util.List;

/**
 * 线程安全分析-局部变量引用
 */
public class ThreadSafeTest001 {

    public static final int THREAD_NUM = 2;

    public static final int LOOP_NUM = 200;

    public static void main(String[] args) {
        ThreadSafe thread = new ThreadSafe();
        for (int i = 0; i < THREAD_NUM; i++) {
            new Thread(() -> {
                thread.method1(LOOP_NUM);
            }).start();
        }
    }

}

class ThreadUnsafe {
    List<Integer> dataList = new ArrayList();

    public void method1(int loopNum) {
        for(int i = 0 ; i < loopNum ; i++){
            try {
                method2();
                method3();
            } catch (Exception e) {
                e.printStackTrace();
                throw e;
            }
        }
    }

    private void method2() {
        dataList.add(1);
    }

    private void method3() {
        dataList.remove(0);
    }
}

class ThreadSafe {

    public void method1(int loopNum) {
        List<Integer> dataList = new ArrayList();
        for(int i = 0 ; i < loopNum ; i++){
            try {
                method2(dataList);
                method3(dataList);
            } catch (Exception e) {
                e.printStackTrace();
                throw e;
            }
        }
    }

    private void method2(List<Integer> dataList) {
        dataList.add(1);
    }

    private void method3(List<Integer> dataList) {
        dataList.remove(0);
    }
}
